package server;

import java.util.Random;
import java.util.Vector;

import server.interfaces.IMobileAgentExecutionEngine;
import server.interfaces.ITimer;
import server.interfaces.ITimerManager;

import com.Constants;
import com.Event;


public class TimerManager implements ITimerManager {
	
	private Vector timerThreads;
	
	private IMobileAgentExecutionEngine executionEngine;
	
	public TimerManager (IMobileAgentExecutionEngine executionEngine) {
		this.timerThreads = new Vector();
		this.executionEngine = executionEngine;
	}
	
	public String generateTimerID() {
		
		return "" + new Random().nextInt(Constants.MAX_TIMER_ID);
	}
	
	public void removeTimer(String timerID) {

		int timerIndex = this.getTimerIndex(timerID);
		if (timerIndex != -1) {
			this.timerThreads.removeElementAt(timerIndex);
			Runtime.getRuntime().gc();
		}
		
	}
	
	public void resetTimer(String timerID) {
		int timerIndex = this.getTimerIndex(timerID);
		if (timerIndex != -1) 
			((ITimer)this.timerThreads.elementAt(timerIndex)).reset();		
	}
	
	public String setTimer(boolean periodic, long timeout, Event backEvent) {
		String timerID = generateTimerID();
		ITimer timer = Factory.getITimer(timerID, this, periodic, timeout, backEvent);
		this.timerThreads.addElement(timer);
		new Thread(timer).start();
		return timerID;
	}

	public IMobileAgentExecutionEngine getExecutionEngine() {
		return this.executionEngine;
	}
	
	private int getTimerIndex(String timerID) {
		
		for (int i = 0; i < timerThreads.size(); i++) {
			ITimer timer = (ITimer)timerThreads.elementAt(i);
			if (timer.getID().equals(timerID)) {
				return i;
			}
		}
		return -1;
	}
	
}
